package com.demo.interceptor;


import com.common.commont.Messageconstant;
import com.tools.Fisco.context.context;
import com.common.result.Result;
import com.tools.untils.jwtutils;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class JwtToken  implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());
        //2、校验令牌
        try {
            log.info("jwt校验");
            Claims claims = jwtutils.parseJWT(jwtProperties.getUserSecretKey(), token);
            String usrID = claims.get(Messageconstant.user_ID).toString();
            context.setCurrtId(usrID);
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            log.error("解析失败:"+ex.getMessage());
            response.setStatus(401);
            Result result = Result.error(Messageconstant.NOT_LOGIN);
            String notlogin = JSONObject.toJSONString(result);
            response.getWriter().write(notlogin);
            return false;
        }
    }
}
